using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using EventScavenger;

namespace EventScavenger
{
    public partial class MachineLogEntryEdit : Form
    {
        public MachineLogEntryEdit()
        {
            InitializeComponent();
        }
        private MachineLogEntry entry;
        private EventScavengerDAL eventScavengerDAL;

        #region Public methods
        public DialogResult ShowMachineLogEntry(EventScavengerDAL sqlEventSource, MachineLogEntry EmptyEntry)
        {
            this.eventScavengerDAL = sqlEventSource;
            this.entry = this.eventScavengerDAL.GetMachineLogEntry(EmptyEntry.Machine, EmptyEntry.LogName);

            LoadCollectors();
            LoadPollFilters();
            LoadDBImportNames();
            cboCollector.Text = this.entry.Collector;
            if (this.entry.PollFilterID > 0)
                cboPollingFilter.Text = this.entry.PollingFilterName;
            txtMachine.Text = this.entry.Machine;
            cboLog.Items.Add(this.entry.LogName);
            cboLog.Text = this.entry.LogName;
            txtLastPollTime.Text = this.entry.LastPollTime.ToString("yyyy-MM-dd HH:mm");
            if (this.entry.Machine.Length > 0)
            {
                txtMachine.ReadOnly = true;
                cboLog.Enabled = true;
                cmdLoadLogs.Visible = false;
                cmdDelete.Visible = true;
                cmdClear.Visible = true;
            }
            if (this.entry.Enabled)
                optEnabled.Checked = true;
            else if (this.entry.DBImportEnabled)
            {
                optImport.Checked = true;
            }
            else
                optDisabled.Checked = true;
            cboServer.Text = this.entry.DBImportServer;
            cboDatabase.Text = this.entry.DBImportDatabase;
            
            frequencyNumericUpDown.Value = this.entry.PollFrequency;
            numericUpDownMaxEntries.Value = this.entry.MaxEntryCount;

            return ShowDialog();
        } 
        #endregion

        #region Button events
        private void cmdLoadLogs_Click(object sender, EventArgs e)
        {
            LoadLogs();
        }
        private void cmdDelete_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Are you absolutely sure you want to delete this event log and all its data?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                try
                {
                    Cursor.Current = Cursors.WaitCursor;
                    eventScavengerDAL.DeleteMachineLog(entry.MachineLogID);
                    this.DialogResult = DialogResult.OK;
                    Close();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    Cursor.Current = Cursors.Default;
                }
            }
        }
        private void cmdClear_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Are you sure you want to clear all event log entries in the database for this machine event log?",
                "Clear", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                try
                {
                    Cursor.Current = Cursors.WaitCursor;
                    this.eventScavengerDAL.ClearAllEntriesForMachineLog(entry.MachineLogID);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Clear", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    Cursor.Current = Cursors.Default;
                }
            }
        }
        private void cmdOK_Click(object sender, EventArgs e)
        {
            DateTime lastPollTime;
            if (cboCollector.SelectedIndex == -1)
            {
                MessageBox.Show("You must specify a collector!", "Collector", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                cboCollector.Focus();
            }
            else if (txtMachine.Text.Length == 0)
            {
                MessageBox.Show("You must specify a machine name!", "Machine", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                txtMachine.Focus();
            }
            else if (cboLog.Text.Length == 0)
            {
                MessageBox.Show("You must specify a log name!", "Log", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                cboLog.Focus();
            }
            else if (optImport.Checked && (cboServer.Text.Length == 0 || cboDatabase.Text.Length == 0))
            {
                MessageBox.Show("You must specify a server and database name for imports!", "Imports", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                cboServer.Focus();
            }
            else if (!DateTime.TryParse(txtLastPollTime.Text, out lastPollTime))
            {
                MessageBox.Show("You must specify a valid date/time for last poll time!", "Last poll time", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                txtLastPollTime.Focus();
            }
            else
            {
                this.entry.CollectorId = ((Collector)cboCollector.SelectedItem).Id;
                this.entry.Machine = txtMachine.Text;
                this.entry.LogName = cboLog.Text;
                this.entry.LastPollTime = DateTime.Parse(txtLastPollTime.Text);
                this.entry.Enabled = optEnabled.Checked;
                this.entry.DBImportEnabled = optImport.Checked;
                this.entry.PollFrequency = (int)frequencyNumericUpDown.Value;
                this.entry.MaxEntryCount = (int)numericUpDownMaxEntries.Value;
                this.entry.PollFilterID = 0;
                if (cboPollingFilter.SelectedItem != null)
                {
                    this.entry.PollFilterID = ((PollFilter)cboPollingFilter.SelectedItem).PollFilterID;
                }
                this.entry.DBImportServer = cboServer.Text;
                this.entry.DBImportDatabase = cboDatabase.Text;
                eventScavengerDAL.UpdateMachineLogEntry(this.entry);
                this.DialogResult = DialogResult.OK;
                Close();
            }
        }
        #endregion

        #region MyRegion
        private void txtLastPollTime_Leave(object sender, EventArgs e)
        {
            try
            {
                txtLastPollTime.Text = DateTime.Parse(txtLastPollTime.Text).ToString("yyyy-MM-dd HH:mm");
            }
            catch
            {
                txtLastPollTime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
            }
        }
        private void txtMachine_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                LoadLogs();
            }
        }
        #endregion

        #region Private methods
        private void LoadCollectors()
        {
            try
            {
                List<Collector> collectors = eventScavengerDAL.GetCollectorList();
                foreach (Collector collector in collectors)
                {
                    cboCollector.Items.Add(collector);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void LoadLogs()
        {
            if (cmdLoadLogs.Enabled)
            {
                cboLog.Items.Clear();
                try
                {
                    if (txtMachine.Text.Length > 0 && System.Net.Dns.GetHostAddresses(txtMachine.Text).Length > 0)
                    {
                        EventLog[] logs = EventLog.GetEventLogs(txtMachine.Text);
                        foreach (EventLog log in logs)
                        {
                            cboLog.Items.Add(log.Log);
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
        private void LoadPollFilters()
        {
            try
            {
                List<PollFilter> pollfilters = eventScavengerDAL.GetPollingFilterList();
                cboPollingFilter.Items.Add(new PollFilter() { PollFilterID = -1, Name = "(None)" });
                foreach (PollFilter pollfilter in pollfilters)
                {
                    cboPollingFilter.Items.Add(pollfilter);
                }
                cboPollingFilter.SelectedIndex = 0;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void LoadDBImportNames()
        {
            try
            {
                List<Tuple<string, string>> list = this.eventScavengerDAL.GetExistingDBImportNames();
                cboServer.Items.Clear();
                cboDatabase.Items.Clear();
                foreach (Tuple<string, string> entry in list)
                {
                    if (entry.Item1.Length > 0 && !cboServer.Items.Contains(entry.Item1))
                        cboServer.Items.Add(entry.Item1);
                    if (entry.Item2.Length > 0 && !cboDatabase.Items.Contains(entry.Item2))
                        cboDatabase.Items.Add(entry.Item2);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Import DB names", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion

        #region Radio button events
        private void optImport_CheckedChanged(object sender, EventArgs e)
        {
            cboServer.Enabled = optImport.Checked;
            cboDatabase.Enabled = optImport.Checked;
        } 
        #endregion


        
    }
}